package com.example.demoapp.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.demoapp.R;
import com.example.demoapp.bean.User;
import com.example.demoapp.brvah.adapter.CollectAdapter;
import com.example.demoapp.brvah.bean.CollectItemBean;
import com.example.demoapp.brvah.bean.MultipleItemBean;
import com.example.demoapp.config.URLs;
import com.example.demoapp.vollley.MySingleton;
import com.google.gson.Gson;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyCollectionActivity extends AppCompatActivity {
    //适配器
    SmartRefreshLayout smartRefreshLayout;
    private SharedPreferences preferences;
    private Context mContext;
    private User user;
    private int page;
    //recyclerView
    private RecyclerView recyclerView;
    //数据列表
    private List<CollectItemBean> dataList;
    //适配器
    private CollectAdapter collectAdapter;
    public static String tabtype_adress[] = {URLs.information_getInformationById,URLs.article_getArticleById,URLs.video_getVideoById,URLs.music_getMusicById};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_collection);
        preferences = getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
        user = new Gson().fromJson(preferences.getString("user",""),User.class);
        smartRefreshLayout = findViewById(R.id.smartRefreshLayout);
        mContext = this;
        page=1;
        //recyclerView
        recyclerView = findViewById(R.id.recycler_view);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setTitle("我的收藏");
            bar.setDisplayHomeAsUpEnabled(true);
            bar.setHomeButtonEnabled(true);
        }

        initRecyclerView();
        initListData(true);

        //刷新监听
        MaterialHeader materialHeader = (MaterialHeader) smartRefreshLayout.getRefreshHeader();
        materialHeader.setColorSchemeColors(getResources().getColor(R.color.theme_color));
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout smartRefreshLayout) {
                page=1;
                initListData(true);
                smartRefreshLayout.finishRefresh();//传入false表示刷新失败
                Toast.makeText(mContext, "刷新成功", Toast.LENGTH_SHORT).show();
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout smartRefreshLayout) {
                page++;
                initListData(false);
                smartRefreshLayout.finishLoadMore();//传入false表示加载失败
            }
        });

    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        // 初始化RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置分割线
        //初始化数据
        dataList = new ArrayList<>();
        //初始化适配器
        collectAdapter = new CollectAdapter(R.layout.layout_collect);
        collectAdapter.setNewInstance(dataList);
        //添加加载动画
        collectAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInLeft);
        //设置空布局
        // collectAdapter.setEmptyView(R.layout.layout_empty);
        //设置适配器
        recyclerView.setAdapter(collectAdapter);
        //设置Item点击事件
        collectAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                CollectItemBean oneMultipleItemBean = dataList.get(position);
                String ID = oneMultipleItemBean.getTargetId();
                int index = oneMultipleItemBean.getTargetType();
                Uri.Builder builder = Uri.parse(tabtype_adress[index]).buildUpon();
                builder.appendQueryParameter("id",ID);
                String url = builder.build().toString();
                MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(Request.Method.GET,url, null,
                        new Response.Listener() {
                            @Override
                            public void onResponse(Object response) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response.toString());
                                    int code = jsonObject.getInt("code");
                                    if (code == 200) {
                                        JSONObject dataObject = jsonObject.getJSONObject("data");
                                        MultipleItemBean multipleItemBean = new Gson().fromJson(dataObject.toString(), MultipleItemBean.class);
                                        changeView(multipleItemBean,index);
                                    }
                                } catch (Exception e) {
                                    Log.i("dochangeCollect出现错误",e.toString());
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();
                    }
                }){
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> headers = new HashMap<>();
                        headers.put("token", user.getToken());
                        return headers;
                    }
                });
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // 再次进入刷新页数
    @Override
    protected void onResume() {
        super.onResume();
        page=1;
    }

    /**
     * 获取数据
     *
     * @return
     */
    private List<CollectItemBean> initListData(boolean isLoad) {
        if (isLoad)dataList.clear();
        String token = preferences.getString("token","");
        HashMap map = new HashMap();
        map.put("page",String.valueOf(page));
        map.put("pageSize","20");
        map.put("status","1");
        MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.collect_list, new JSONObject(map),
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.toString());
                            int code = jsonObject.getInt("code");
                            if (code == 200) {
                                JSONObject jdata = jsonObject.getJSONObject("data");
                                // 从JSONObject中获取"data"字段对应的JSONArray
                                JSONArray dataArray = jdata.getJSONArray("records");
                                // 遍历JSONArray并解析每个对象
                                if (dataArray.length()==0) {
                                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                for (int i = 0; i < dataArray.length(); i++) {
                                    JSONObject dataObject = dataArray.getJSONObject(i);
                                    CollectItemBean collectItemBean = new Gson().fromJson(dataObject.toString(), CollectItemBean.class);
                                    dataList.add(collectItemBean);
                                    Log.d("collectItemBean", collectItemBean.toString());
                                }
                                collectAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            Log.i("加载列表错误",e.toString());
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("token", token);
                return headers;
            }
        });
        return dataList;
    }

    private void changeView(MultipleItemBean oneMultipleItemBean,int index){
        if (oneMultipleItemBean.isSource().equals("1") && oneMultipleItemBean.getLink().startsWith("h")){
            Uri uri = Uri.parse(oneMultipleItemBean.getLink());
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.setData(uri);
            startActivity(intent);
        } else{
            String html = oneMultipleItemBean.getLink();
            String name = oneMultipleItemBean.getId();
            Intent i = new Intent();
            switch (index){
                case 0:
                    i = new Intent(mContext, DocumentsDisplayActivity.class);
                    i.putExtra("downloadEnable",oneMultipleItemBean.isDownload());
                    html = oneMultipleItemBean.getRichText();
                    break;
                case 1:
                    i = new Intent(mContext, InformationDisplayActivity.class);
                    html = oneMultipleItemBean.getRichText();
                    break;
                case 2:
                    i = new Intent(mContext, VideoDisplayActivity.class);
                    break;
                case 3:
                    i = new Intent(mContext, AudioPlayActivity.class);
                    break;
            };
            i.putExtra("isLiked", oneMultipleItemBean.getIsAgree());
            i.putExtra("isCollected", oneMultipleItemBean.getIsCollect());
            i.putExtra("LINK", html);
            i.putExtra("NAME", name);
            mContext.startActivity(i);
        }

    }
}